/**
 * Created by houyefeng on 2015-10-09.
 */
package com.emar.adx.yiqifa.util;

import org.apache.commons.lang.StringUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * base64加密工具类。
 *
 * @author houyefeng
 * @version 4.1.0
 * @since 4.1.0 2015-10-09
 */
public class EncryptBase64 {
    private final static String CHARACTER_SET = "UTF-8";

    public final static String decoder(String s) {
        return decoder(s, null, null);
    }

    public final static String decoder(String s, String key) {
        return decoder(s, CHARACTER_SET, null);
    }

    public final static String decoder(String s, String characterSet, String key) {
        BASE64Decoder b64 = new BASE64Decoder();
        /*
         * 由于有些web容器（如tomcat 6以后，6之前的没有进行测试）会将cookie中取到的值后面的‘=’去掉，
         * 这样程序得到的值就有可能不是放进cookie中的
         * base64编码串，导致不能正常解码，所以需要根据情况补上1个或2个‘=’。
         */
        if (!s.endsWith("=")) {
            switch (s.length() % 4) {
                case 3:
                    s += "==";
                    break;
                case 2:
                    s += "==";
                    break;
                case 1:
                    s += "=";
                    break;
                default:
            }
        }

        String decode = null;
        try {
            decode = new String(b64.decodeBuffer(s));
            if (StringUtils.isNotBlank(characterSet) && StringUtils.isNotBlank(key)) {
                decode = replacement(decode, key, characterSet);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return decode;
    }

    public final static String encoder(String s) {
        return encoder(s, CHARACTER_SET, null);
    }

    public final static String encoder(String s, String key) {
        return encoder(s, CHARACTER_SET, key);
    }

    public final static String encoder(String s, String characterSet, String key) {
        BASE64Encoder b64 = new BASE64Encoder();
        String src = s;
        if (StringUtils.isNotBlank(key)) {
            src = replacement(s, characterSet, key);
        }
        String encode = null;
        try {
            encode = new String(b64.encode(src.getBytes(characterSet)));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        encode = encode.replaceAll(" ", "").replaceAll("\r", "").replaceAll("\n", "");
        return encode;
    }

    private static String replacement(String src, String key, String characterSet) {
        String result = null;
        try {
            byte[] keyBytes = key.getBytes(characterSet);
            int keyLen = keyBytes.length;
            byte[] srcBytes = src.getBytes(characterSet);
            int len = srcBytes.length;
            byte[] bb = new byte[len];
            for (int i = 0; i < len; i++) {
                int k = i % keyLen;
                byte b = (byte) (srcBytes[i] ^ keyBytes[k]);
                bb[i] = b;
            }
            result = new String(bb);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return result;
    }
}
